<template>
  <div class="myAutocomplete">
    <el-autocomplete v-model.lazy="childModel"
                     popper-class="myAutocomplete-popper"
                     placeholder="请输入"
                     :trigger-on-focus="false"
                     :hide-loading="true"
                     :readonly="readonly"
                     :fetch-suggestions="querySearch"
                     @select="((item)=>{handleSelect(item)})"
                     :disabled="disabled"
                     class="el-form-item_all_input"
    >
      <!--handleSelect-->
      <slot name="autoCompleteSlot" :slot="slotType"></slot>
    </el-autocomplete>
  </div>
</template>

<script>

export default {
  name: 'myAutocomplete',
  props: {
    // 当前组件绑定值
    model: {
      type: String,
      require: true
    },
    // 下拉选项
    options: {
      type: Array,
      default () {
        return [{label: '全部', value: '0'}]
      }
    },
    // 输入建议对象中用于显示的键名
    valueKey: {
      type: String,
      default () {
        return 'label'
      }
    },
    // 当前组件slot插槽类型prefix、suffix、prepend、append
    slotType: {
      type: String,
      default () {
        return ''
      }
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default () {
        return false
      }
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default () {
        return false
      }
    }
  },
  data () {
    return {
      childModel: this.model
    }
  },
  watch: {
    childModel (val) {
      this.$emit('update:model', val)
    },
    model (val) {
      if (val !== this.childModel) {
        this.childModel = val
      }
    }
  },
  created () {
  },
  methods: {
    querySearch (queryString, cb) {
      // 当前搜索过滤方法
      const options = this.options
      let results = queryString ? options.filter(this.createFilter(queryString)) : options
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter (queryString) {
      // 过滤条件
      return (options) => {
        return this.filter(options, queryString)
      }
    },
    filter (options, queryString) {
      return options[this.valueKey].toLowerCase().indexOf(queryString.toLowerCase()) === 0
    },
    handleSelect (item) {
      console.log(item)
    }
  }
}
</script>

<style lang="scss">
  .myAutocomplete-popper {
    .el-autocomplete-suggestion__wrap {
      overflow: scroll;
      li {
        line-height: normal;
        padding-top: 7px;
        padding-bottom: 7px;
      }
    }
  }

</style>
